﻿namespace WMS6.SQLServerDAL
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Common;
    using System.Data.SqlClient;
    using WMS6.Common;
    using WMS6.DataEntity;
    using WMS6.DBUtility;
    using WMS6.IDAL;
    using WMS6.QueryEntity;

    public class StatementDA : IStatementDA
    {
        private string CREATED_BY = "@CREATED_BY";
        private string END_TIME = "@END_TIME";
        private string OWNER_ID = "@OWNER_ID";
        private string PAYMENT_DATE = "@PAYMENT_DATE";
        private string REMARK = "@REMARK";
        private string SQL_CHECK_STATEMENT_ID_UNIQUE = " SELECT COUNT(1) FROM @_@STATEMENT WHERE STATEMENT_ID = @STATEMENT_ID ";
        private string SQL_DELETE_STATEMENT = " DELETE FROM @_@STATEMENT WHERE STATEMENT_ID = @STATEMENT_ID ";
        private string SQL_INSERT_STATEMENT = " INSERT INTO @_@STATEMENT ( WH_ID, STATEMENT_ID, OWNER_ID, STATUS, STATEMENT_DATE, START_TIME, END_TIME, PAYMENT_DATE, REMARK, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE) VALUES ( @WH_ID, @STATEMENT_ID, @OWNER_ID, @STATUS, @STATEMENT_DATE, @START_TIME, @END_TIME, @PAYMENT_DATE, @REMARK, @CREATED_BY, GETDATE(), @UPDATED_BY, GETDATE() )  ";
        private string SQL_SELECT_ALL_STATEMENT = " SELECT  ROWID, WH_ID, STATEMENT_ID, OWNER_ID, STATUS, STATEMENT_DATE, START_TIME, END_TIME, PAYMENT_DATE, REMARK, CREATED_BY, CREATED_DATE, UPDATED_BY, UPDATED_DATE  FROM  @_@STATEMENT ";
        private string SQL_SELECT_ALL_STATEMENT_LANGUAGE = "SELECT  S.ROWID, S.WH_ID, S.STATEMENT_ID, S.OWNER_ID, S.STATUS,T.[TEXT] AS STATUS_D,S.STATEMENT_DATE, S.START_TIME, S.END_TIME, S.REMARK, S.CREATED_BY, S.CREATED_DATE, S.UPDATED_BY, S.UPDATED_DATE FROM  @_@STATEMENT S LEFT JOIN @_@SYS_CODE_DETAIL SCD ON SCD.SYS_CODE = S.STATUS AND SCD.SYS_CODE_TYPE = 'StatementStatu' LEFT JOIN sysadm.TRANSLATION T ON 'StatementStatu.'+S.STATUS = T.ITEM_ID AND  T.ITEM_TYPE = 'SYS_CODE_DETAIL'  AND  T.LANG+'-'+T.COUNTRY = @LANGUAGE INNER JOIN SYSADM.USER_OWNER UO ON S.OWNER_ID = UO.OWNER_ID AND  UO.[USER_ID] = @USER_ID ";
        private string SQL_UPDATE_STATEMENT = " UPDATE @_@STATEMENT SET WH_ID = @WH_ID, OWNER_ID = @OWNER_ID, STATUS = @STATUS, STATEMENT_DATE = @STATEMENT_DATE, START_TIME = @START_TIME, END_TIME = @END_TIME, PAYMENT_DATE = @PAYMENT_DATE, REMARK = @REMARK, UPDATED_BY = @UPDATED_BY, UPDATED_DATE = GETDATE() WHERE STATEMENT_ID = @STATEMENT_ID  ";
        private string START_TIME = "@START_TIME";
        private string STATEMENT_DATE = "@STATEMENT_DATE";
        private string STATEMENT_ID = "@STATEMENT_ID";
        private string STATUS = "@STATUS";
        private string UPDATED_BY = "@UPDATED_BY";
        private string WH_ID = "@WH_ID";

        public bool CheckStatementIDUnique(string statementID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATEMENT_ID", statementID) };
            return (DBHelper.ExecuteScalar(CommandType.Text, this.SQL_CHECK_STATEMENT_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public bool CheckStatementIDUnique(DataBase dataBase, DbTransaction tran, string statementID, string whLoginID)
        {
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATEMENT_ID", statementID) };
            return (dataBase.ExecuteScalar(tran, CommandType.Text, this.SQL_CHECK_STATEMENT_ID_UNIQUE.Replace("@_@", whLoginID), paras).ToString() == "1");
        }

        public int DeleteStatement(List<string> statementID, string whLoginID)
        {
            int result = 0;
            DataBase dataBase = new DataBase();
            DbConnection conn = dataBase.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                for (int j = 0; j < statementID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATEMENT_ID", statementID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_STATEMENT.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int DeleteStatement(DataBase dataBase, DbTransaction tran, List<string> statementID, string whLoginID)
        {
            int result = 0;
            try
            {
                for (int j = 0; j < statementID.Count; j++)
                {
                    SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATEMENT_ID", statementID[j]) };
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_DELETE_STATEMENT.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        public DataSet GetAllStatement(string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_STATEMENT.Replace("@_@", whLoginID);
            return DBHelper.ExecuteDataSet(CommandType.Text, sql);
        }

        public DataSet GetAllStatement(DataBase dataBase, DbTransaction tran, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_STATEMENT.Replace("@_@", whLoginID);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, sql);
        }

        public StatementInfo GetStatementByID(string statementID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_STATEMENT.Replace("@_@", whLoginID) + " WHERE STATEMENT_ID = @STATEMENT_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATEMENT_ID", statementID) };
            StatementInfo statementInfo = null;
            using (IDataReader reader = DBHelper.ExecuteReader(CommandType.Text, sql, paras))
            {
                if (reader.Read())
                {
                    DateTime CS00003;
                    statementInfo = new StatementInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["STATEMENT_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["STATUS"].ToString(), (reader["STATEMENT_DATE"].ToString() != "") ? DateTime.Parse(reader["STATEMENT_DATE"].ToString()) : (CS00003 = new DateTime()), (reader["START_TIME"].ToString() != "") ? DateTime.Parse(reader["START_TIME"].ToString()) : (CS00003 = new DateTime()), (reader["END_TIME"].ToString() != "") ? DateTime.Parse(reader["END_TIME"].ToString()) : (CS00003 = new DateTime()), reader["REMARK"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00003 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00003 = new DateTime()), (reader["PAYMENT_DATE"].ToString() != "") ? DateTime.Parse(reader["PAYMENT_DATE"].ToString()) : new DateTime());
                }
            }
            return statementInfo;
        }

        public StatementInfo GetStatementByID(DataBase dataBase, DbTransaction tran, string statementID, string whLoginID)
        {
            string sql = this.SQL_SELECT_ALL_STATEMENT.Replace("@_@", whLoginID) + " WHERE STATEMENT_ID = @STATEMENT_ID  ";
            SqlParameter[] paras = new SqlParameter[] { new SqlParameter("@STATEMENT_ID", statementID) };
            StatementInfo statementInfo = null;
            IDataReader reader = dataBase.ExecuteReader(tran, CommandType.Text, sql, paras);
            if (reader.Read())
            {
                DateTime CS00003;
                statementInfo = new StatementInfo((reader["ROWID"].ToString() != "") ? int.Parse(reader["ROWID"].ToString()) : 0, reader["WH_ID"].ToString(), reader["STATEMENT_ID"].ToString(), reader["OWNER_ID"].ToString(), reader["STATUS"].ToString(), (reader["STATEMENT_DATE"].ToString() != "") ? DateTime.Parse(reader["STATEMENT_DATE"].ToString()) : (CS00003 = new DateTime()), (reader["START_TIME"].ToString() != "") ? DateTime.Parse(reader["START_TIME"].ToString()) : (CS00003 = new DateTime()), (reader["END_TIME"].ToString() != "") ? DateTime.Parse(reader["END_TIME"].ToString()) : (CS00003 = new DateTime()), reader["REMARK"].ToString(), reader["CREATED_BY"].ToString(), (reader["CREATED_DATE"].ToString() != "") ? DateTime.Parse(reader["CREATED_DATE"].ToString()) : (CS00003 = new DateTime()), reader["UPDATED_BY"].ToString(), (reader["UPDATED_DATE"].ToString() != "") ? DateTime.Parse(reader["UPDATED_DATE"].ToString()) : (CS00003 = new DateTime()), (reader["PAYMENT_DATE"].ToString() != "") ? DateTime.Parse(reader["PAYMENT_DATE"].ToString()) : new DateTime());
            }
            if (!reader.IsClosed)
            {
                reader.Close();
            }
            return statementInfo;
        }

        public DataSet GetStatementByQueryList(List<string> sqlWhere, StatementQueryEntity statementQuery, string whLoginID, PubParasInfo pubParasInfo)
        {
            string temp = this.SQL_SELECT_ALL_STATEMENT_LANGUAGE.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            if (!statementQuery.IsGetAll)
            {
                temp = PagingHelper.GetPagingSQL(temp, statementQuery.CurrentPage, statementQuery.PageSize, statementQuery.SortField, statementQuery.SortDirection).Replace("@LANGUAGE", "''" + pubParasInfo.UserLanguage + "''").Replace("@USER_ID", "''" + pubParasInfo.UserID + "''");
            }
            else
            {
                temp = temp.Replace("@LANGUAGE", "'" + pubParasInfo.UserLanguage + "'").Replace("@USER_ID", "'" + pubParasInfo.UserID + "'");
            }
            return DBHelper.ExecuteDataSet(CommandType.Text, temp);
        }

        public DataSet GetStatementByQueryList(DataBase dataBase, DbTransaction tran, List<string> sqlWhere, StatementQueryEntity statementQuery, string whLoginID)
        {
            string temp = this.SQL_SELECT_ALL_STATEMENT.Replace("@_@", whLoginID);
            for (int i = 0; i < sqlWhere.Count; i++)
            {
                if (i == 0)
                {
                    temp = temp + " WHERE " + sqlWhere[i].ToString();
                }
                else
                {
                    temp = temp + " AND " + sqlWhere[i].ToString();
                }
            }
            temp = PagingHelper.GetPagingSQL(temp, statementQuery.CurrentPage, statementQuery.PageSize, statementQuery.SortField, statementQuery.SortDirection);
            return dataBase.ExecuteDataSet(tran, CommandType.Text, temp);
        }

        public int InsertStatement(StatementInfo statementInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                statementInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Statement_Parameters(statementInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_STATEMENT.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int InsertStatement(DataBase dataBase, DbTransaction tran, StatementInfo statementInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                statementInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Statement_Parameters(statementInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_INSERT_STATEMENT.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }

        private SqlParameter[] Set_Statement_Parameters(StatementInfo statementInfo)
        {
            SqlParameter[] paramArray = new SqlParameter[] { new SqlParameter(this.WH_ID, SqlDbType.VarChar, 30), new SqlParameter(this.STATEMENT_ID, SqlDbType.VarChar, 20), new SqlParameter(this.OWNER_ID, SqlDbType.VarChar, 20), new SqlParameter(this.STATUS, SqlDbType.VarChar, 20), new SqlParameter(this.STATEMENT_DATE, SqlDbType.DateTime, 8), new SqlParameter(this.START_TIME, SqlDbType.DateTime, 8), new SqlParameter(this.END_TIME, SqlDbType.DateTime, 8), new SqlParameter(this.PAYMENT_DATE, SqlDbType.DateTime, 8), new SqlParameter(this.REMARK, SqlDbType.VarChar, 100), new SqlParameter(this.CREATED_BY, SqlDbType.VarChar, 20), new SqlParameter(this.UPDATED_BY, SqlDbType.VarChar, 20) };
            if (!string.IsNullOrEmpty(statementInfo.WhID))
            {
                paramArray[0].Value = statementInfo.WhID;
            }
            else
            {
                paramArray[0].Value = DBNull.Value;
            }
            paramArray[1].Value = statementInfo.StatementID;
            paramArray[2].Value = statementInfo.OwnerID;
            paramArray[3].Value = statementInfo.Status;
            DateTime CS00003 = new DateTime();
            if (statementInfo.StatementDate != CS00003)
            {
                paramArray[4].Value = statementInfo.StatementDate;
            }
            else
            {
                paramArray[4].Value = DBNull.Value;
            }
            paramArray[5].Value = statementInfo.StartTime;
            paramArray[6].Value = statementInfo.EndTime;
            if (statementInfo.PaymentDate != new DateTime())
            {
                paramArray[7].Value = statementInfo.PaymentDate;
            }
            else
            {
                paramArray[7].Value = DBNull.Value;
            }
            if (!string.IsNullOrEmpty(statementInfo.Remark))
            {
                paramArray[8].Value = statementInfo.Remark;
            }
            else
            {
                paramArray[8].Value = DBNull.Value;
            }
            paramArray[9].Value = statementInfo.CreatedBy;
            paramArray[10].Value = statementInfo.UpdatedBy;
            return paramArray;
        }

        public int UpdateStatement(StatementInfo statementInfo, string whLoginID)
        {
            int result = 0;
            DataBase db = new DataBase();
            DbConnection conn = db.connection;
            conn.Open();
            DbTransaction tran = conn.BeginTransaction();
            try
            {
                statementInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Statement_Parameters(statementInfo);
                if (paras != null)
                {
                    result += db.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_STATEMENT.Replace("@_@", whLoginID), paras);
                }
                tran.Commit();
            }
            catch (SqlException sqlEx)
            {
                tran.Rollback();
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

        public int UpdateStatement(DataBase dataBase, DbTransaction tran, StatementInfo statementInfo, string whLoginID)
        {
            int result = 0;
            try
            {
                statementInfo.WhID = whLoginID.Substring(0, whLoginID.Length - 1);
                SqlParameter[] paras = this.Set_Statement_Parameters(statementInfo);
                if (paras != null)
                {
                    result += dataBase.ExecuteNonQuery(tran, CommandType.Text, this.SQL_UPDATE_STATEMENT.Replace("@_@", whLoginID), paras);
                }
            }
            catch (SqlException sqlEx)
            {
                CommonErrorHandler.ErrorHandler(sqlEx, LogType.Error);
            }
            return result;
        }
    }
}

